package net.lulihu.common_util.converter;

import lombok.extern.slf4j.Slf4j;
import net.lulihu.dateTime.DateTimeKit;
import org.springframework.core.convert.converter.Converter;

import java.util.Date;
import java.util.regex.Pattern;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

/**
 * 请求中时间字符串转换为时间对象
 * <p>
 * 使用方式:
 * <pre>
 * {@link org.springframework.beans.factory.annotation.Autowired}
 *   private {@link RequestMappingHandlerAdapter} handlerAdapter;
 *
 * {@link javax.annotation.PostConstruct}
 * public void addConversionConfig() {
 *   ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer();
 *   GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
 *   genericConversionService.addConverter(new StringToDateConverter());
 * }
 * </pre>
 * <p>
 * 注意：
 * 依赖注入{@link RequestMappingHandlerAdapter}的配置对象不能实现{@link WebMvcConfigurer}
 * 否则将导致 {@link RequestMappingHandlerAdapter} 实例化被提前。
 *
 * @see WebMvcConfigurationSupport#applicationContext applicationContext 还未被注入，导致导出抛出空指针异常
 */
@Slf4j
public class StringToDateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String dateString) {
        // 时间格式 yyyy-MM-dd
        String patternDate = "\\d{4}-\\d{1,2}-\\d{1,2}";
        boolean dateFlag = Pattern.matches(patternDate, dateString);
        if (dateFlag) {
            return DateTimeKit.parseDate(dateString);
        }
        // 时间格式 yyyy-MM-dd HH:mm
        String patternTimeMinutes = "\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}";
        boolean timeMinutesFlag = Pattern.matches(patternTimeMinutes, dateString);
        if (timeMinutesFlag) {
            return DateTimeKit.parseTimeMinutes(dateString);
        }
        //时间格式 yyyy-MM-dd HH:mm:ss
        String patternTimeSeconds = "\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}";
        boolean timeSecondsFlag = Pattern.matches(patternTimeSeconds, dateString);
        if (timeSecondsFlag) {
            return DateTimeKit.parseDateTime(dateString);
        }
        log.warn("时间字符串【{}】因格式不匹配，未能转换为Date对象...");
        return null;
    }
}